#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGraphicsRectItem>
#include <QTime>
#include <QPointF>
#include <QGraphicsLineItem>
#include <QInputDialog>
#include <QColorDialog>
#include <QFontDialog>
#include <QKeyEvent>
#include <QtMath>
#include <QFileDialog>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>
#include "symbollibrarydialog.h"

/*
 ****开发日志****
 *
 * 1.创建界面
 *  两个toolBar
 *  一个GraphicsView(作为中心部件)
 *
 * 2.对GraphicsView做部件升级
 *  重写4个事件处理
 *  添加4个信号
 *  在4个事件处理集中，获取视图坐标，并发送对应信号，同时把视图坐标传递出去
 *
 * 3.在MainWindow中处理这四个信号
 *  设置鼠标拖拽模式，光标样式，鼠标追踪
 *  4个对应信号的槽函数
 *
 * 4.初始化Scene
 *
 * 5.实现各图形项的绘制
 *
 * 6.实现缩放等功能
 *
 * 7.添加状态栏标签
 *
 ***************/

template<class T>
void setBrushColor(T *item)
{
    QColor color = item->brush().color();
    color = QColorDialog::getColor(color,NULL,"请选择笔刷颜色");
    if(color.isValid())
    {
        item->setBrush(QBrush(color));
    }
}

template<class T>
void setPenColor(T *item)
{
    QColor color = item->pen().color();
    color = QColorDialog::getColor(color,NULL,"请选择画笔颜色");
    if(color.isValid())
    {
        QPen pen;
        pen.setColor(color);
        pen.setWidth(5);
        item->setPen(pen);
    }
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    initView();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initView()
{
    setWindowTitle("2022091603001冯崇浩的CAD");

    setCentralWidget(ui->graphicsView);
    ui->graphicsView->setDragMode(QGraphicsView::RubberBandDrag);//缩放框拖拽模式：橡皮筋模式
    ui->graphicsView->setCursor(Qt::CrossCursor); //十字光标
    ui->graphicsView->setMouseTracking(true);

    scene = new QGraphicsScene(-300,-100,600,200);
    ui->graphicsView->setScene(scene); //4.

    //connect(ui->graphicsView, SIGNAL(keyPress(QKeyEvent*)), this, SLOT(on_graphicsView_keyPress(QKeyEvent*)));
    //connect(ui->graphicsView, SIGNAL(mouseDoubleClick(QPoint)), this, SLOT(on_graphicsView_mouseDoubleClick(QPoint)));

    //自定义网格背景
    connect(scene,&QGraphicsScene::changed,this,[this](const QList<QRectF> &){drawGridBackground();});

    labelView = new QLabel("视图坐标：");
    labelView->setMaximumWidth(200);
    labelView->setMinimumWidth(200);
    labelScene = new QLabel("背景坐标：");
    labelScene->setMaximumWidth(200);
    labelScene->setMinimumWidth(200);
    labelItem = new QLabel("图形项坐标：");
    labelItem->setMaximumWidth(200);
    labelItem->setMinimumWidth(200);
    labelInfo = new QLabel("图形项信息：");
    labelInfo->setMaximumWidth(300);
    labelInfo->setMinimumWidth(300);
    ui->statusbar->addWidget(labelView);
    ui->statusbar->addWidget(labelScene);
    ui->statusbar->addWidget(labelItem);
    ui->statusbar->addWidget(labelInfo);

}

void MainWindow::on_graphicsView_keyPress(QKeyEvent *event)
{
    //使用键盘只能操作一个图形项，更加精准
    if(scene->selectedItems().count() != 1)
    {
        return;
    }
    QGraphicsItem *item = scene->selectedItems().at(0);

    if(event->key() == Qt::Key_Delete)
    {
        scene->removeItem(item);
    }
    else if(event->key() == Qt::Key_Space)
    {
        item->setRotation(item->rotation() + 10);
    }
    else if(event->key() == Qt::Key_PageUp)
    {
        item->setScale(item->scale() + 0.1);
    }
    else if(event->key() == Qt::Key_PageDown)
    {
        item->setScale(item->scale() - 0.1);
    }
    else if(event->key() == Qt::Key_Left)
    {
        item->setX(item->x() - 2);
    }
    else if(event->key() == Qt::Key_Right)
    {
        item->setX(item->x() + 2);
    }
    else if(event->key() == Qt::Key_Up)
    {
        item->setY(item->y() - 2);
    }
    else if(event->key() == Qt::Key_Up)
    {
        item->setY(item->y() + 2);
    }
}

void MainWindow::on_graphicsView_mouseDoubleClick(QPoint point)
{
    //双击图形项设置图形项颜色，双击文本图形项设置字体
    QPointF pointScene = ui->graphicsView->mapToScene(point);
    QGraphicsItem *item = scene->itemAt(pointScene,ui->graphicsView->transform()/*转换矩阵*/);
    if(!item)
    {
        return;
    }

    switch (item->type())
    {
        case QGraphicsRectItem::Type :
        {
            QGraphicsRectItem *item2 = qgraphicsitem_cast<QGraphicsRectItem*>(item);  // < > 后面不要忘记括号 ( )
            if(item2) //检查是否转换成功，若失败会返回nullptr
            {
                //使用模板函数优化
                setBrushColor(item2);
            }
            break;
        }
        case QGraphicsEllipseItem::Type :
        {
            QGraphicsEllipseItem *item2 = qgraphicsitem_cast<QGraphicsEllipseItem*>(item);
            if(item2)
            {
                setBrushColor(item2);
            }
            break;
        }
        case QGraphicsPolygonItem::Type :
        {
            QGraphicsPolygonItem *item2 = qgraphicsitem_cast<QGraphicsPolygonItem*>(item);
            if(item2)
            {
                setBrushColor(item2);
            }
            break;
        }
        case QGraphicsLineItem::Type :
        {
            QGraphicsLineItem *item2 = qgraphicsitem_cast<QGraphicsLineItem*>(item);
            if(item2)
            {
                setPenColor(item2);
            }
            break;
        }
        case QGraphicsTextItem::Type :
        {
            QGraphicsTextItem *item2 = qgraphicsitem_cast<QGraphicsTextItem*>(item);
            QFont font = item2->font(); //item2是转换后的TextItem，应该取item2的字体
            bool ok = false;
            font = QFontDialog::getFont(&ok,font,this,"请选择字体");
            if(ok)
            {
            item2->setFont(font);
            }
            break;
        }
    }
}

void MainWindow::on_graphicsView_mousePress(QPoint point)
{
    QPointF pointScene = ui->graphicsView->mapToScene(point);
    QGraphicsItem *item = scene->itemAt(pointScene,ui->graphicsView->transform());
    if(item)
    {
    QPointF pointItem = item->mapFromScene(pointScene);
    labelItem->setText(QString::asprintf("图形项坐标：%.0f,%.0f",pointItem.x(),pointItem.y()));
    labelInfo->setText("图形项信息：" + item->data(ITEM_DESCRIPTION).toString() + "   图形项ID：" + item->data(ITEM_ID).toString());
    }
}

void MainWindow::on_graphicsView_mouseMove(QPoint point)
{
    QPointF pointScene = ui->graphicsView->mapToScene(point);
    labelScene->setText(QString::asprintf("背景坐标：%.0f,%.0f",pointScene.x(),pointScene.y()));
    labelView->setText(QString::asprintf("全局坐标：%d,%d",point.x(),point.y()));
}


void MainWindow::on_actionRectangle_triggered()
{
    QGraphicsRectItem *item = new QGraphicsRectItem(-20,-10,40,20);
    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    item->setBrush(Qt::lightGray);

    qsrand(QTime::currentTime().second());
    QPointF randomPos(qrand()%100-50,qrand()%100-50);

    // 获取边界矩形左上角
    QRectF boundingRect = item->boundingRect();
    QPointF topLeftOffset = boundingRect.topLeft();

    // 对齐到网格
    const int gridSize = 20;
    qreal alignedX = round((randomPos.x() + topLeftOffset.x()) / gridSize) * gridSize;
    qreal alignedY = round((randomPos.y() + topLeftOffset.y()) / gridSize) * gridSize;

    // 设置图形项位置
    item->setPos(alignedX - topLeftOffset.x(), alignedY - topLeftOffset.y());

    //图形项的Z轴值，越大图层越靠上
    item->setZValue(zValue++);
    //图形项的自定义数据，   键值 ,  数据
    item->setData(ITEM_ID,item_id++);
    item->setData(ITEM_DESCRIPTION,"矩形");

    scene->addItem(item);
    scene->clearSelection(); //清空先前对图形项的选择
    item->setSelected(true); //将新生成的图形项设为选中
}

void MainWindow::on_actionEllipse_triggered()
{
    QGraphicsEllipseItem *item = new QGraphicsEllipseItem(-20,-10,40,20);
    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    item->setBrush(Qt::darkYellow);

    qsrand(QTime::currentTime().second());
    QPointF randomPos(qrand()%100-50,qrand()%100-50);

    // 获取边界矩形左上角
    QRectF boundingRect = item->boundingRect();
    QPointF topLeftOffset = boundingRect.topLeft();

    // 对齐到网格
    const int gridSize = 20;
    qreal alignedX = round((randomPos.x() + topLeftOffset.x()) / gridSize) * gridSize;
    qreal alignedY = round((randomPos.y() + topLeftOffset.y()) / gridSize) * gridSize;

    // 设置图形项位置
    item->setPos(alignedX - topLeftOffset.x(), alignedY - topLeftOffset.y());

    //图形项的Z轴值，越大图层越靠上
    item->setZValue(zValue++);
    //图形项的自定义数据，   键值 ,  数据
    item->setData(ITEM_ID,item_id++);
    item->setData(ITEM_DESCRIPTION,"椭圆形");

    scene->addItem(item);
    scene->clearSelection(); //清空先前对图形项的选择
    item->setSelected(true); //将新生成的图形项设为选中
}

void MainWindow::on_actionCircle_triggered()
{
    QGraphicsEllipseItem *item = new QGraphicsEllipseItem(-20,-20,40,40);
    item->setFlags(QGraphicsItem::ItemIsMovable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsSelectable);
    item->setBrush(Qt::yellow);

    qsrand(QTime::currentTime().second());
    QPointF randomPos(qrand()%100-50,qrand()%100-50);

    // 获取边界矩形左上角
    QRectF boundingRect = item->boundingRect();
    QPointF topLeftOffset = boundingRect.topLeft();

    // 对齐到网格
    const int gridSize = 20;
    qreal alignedX = round((randomPos.x() + topLeftOffset.x()) / gridSize) * gridSize;
    qreal alignedY = round((randomPos.y() + topLeftOffset.y()) / gridSize) * gridSize;

    // 设置图形项位置
    item->setPos(alignedX - topLeftOffset.x(), alignedY - topLeftOffset.y());

    //图形项的Z轴值，越大图层越靠上
    item->setZValue(zValue++);
    //图形项的自定义数据，   键值 ,  数据
    item->setData(ITEM_ID,item_id++);
    item->setData(ITEM_DESCRIPTION,"圆形");

    scene->addItem(item);
    scene->clearSelection(); //清空先前对图形项的选择
    item->setSelected(true); //将新生成的图形项设为选中
}

void MainWindow::on_actionTriangle_triggered()
{
    QGraphicsPolygonItem *item = new QGraphicsPolygonItem;
    item->setFlags(QGraphicsItem::ItemIsSelectable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsMovable);
    QPointF points[3] = {
      {0,-40},
      {-20,0},
      {20,0}
    };
    //创建QPolygonF并添加这些点
    QPolygonF polygon;
    polygon << points[0] << points[1] << points[2];
    //item设置polygon
    item->setPolygon(polygon);
    item->setBrush(Qt::green);

    item->setZValue(zValue++);
    item->setData(ITEM_ID,item_id++);
    item->setData(ITEM_DESCRIPTION,"三角形");
    QPointF randomPos(qrand()%100-60,qrand()%100-60);

    // 获取边界矩形左上角
    QRectF boundingRect = item->boundingRect();
    QPointF topLeftOffset = boundingRect.topLeft();

    // 对齐到网格
    const int gridSize = 20;
    qreal alignedX = round((randomPos.x() + topLeftOffset.x()) / gridSize) * gridSize;
    qreal alignedY = round((randomPos.y() + topLeftOffset.y()) / gridSize) * gridSize;

    // 设置图形项位置
    item->setPos(alignedX - topLeftOffset.x(), alignedY - topLeftOffset.y());

    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actionTrapezoid_triggered()
{
    QGraphicsPolygonItem *item = new QGraphicsPolygonItem;
    item->setFlags(QGraphicsItem::ItemIsSelectable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsMovable);
    QPointF points[4] = {
      {11,-13},
      {-11,-13},
      {-20,13},
      {20,13}
    };
    //创建QPolygonF并添加这些点
    QPolygonF polygon;
    polygon << points[0] << points[1] << points[2] << points[3];
    //item设置polygon
    item->setPolygon(polygon);
    item->setBrush(Qt::blue);

    item->setZValue(zValue++);
    item->setData(ITEM_ID,item_id++);
    item->setData(ITEM_DESCRIPTION,"梯形");
    QPointF randomPos(qrand()%100-60,qrand()%100-60);

    // 获取边界矩形左上角
    QRectF boundingRect = item->boundingRect();
    QPointF topLeftOffset = boundingRect.topLeft();

    // 对齐到网格
    const int gridSize = 20;
    qreal alignedX = round((randomPos.x() + topLeftOffset.x()) / gridSize) * gridSize;
    qreal alignedY = round((randomPos.y() + topLeftOffset.y()) / gridSize) * gridSize;

    // 设置图形项位置
    item->setPos(alignedX - topLeftOffset.x(), alignedY - topLeftOffset.y());

    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actionLine_triggered()
{
    QGraphicsLineItem *item = new QGraphicsLineItem(0,-40,0,40);
    item->setFlags(QGraphicsItem::ItemIsSelectable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsMovable);
    QPen pen;
    pen.setWidth(3);
    pen.setColor(Qt::black);
    pen.setStyle(Qt::SolidLine);
    item->setPen(pen);

    item->setZValue(zValue++);
    item->setData(ITEM_ID,item_id++);
    item->setData(ITEM_DESCRIPTION,"直线");
    QPointF randomPos(qrand()%100-60,qrand()%100-60);

    // 获取边界矩形左上角
    QRectF boundingRect = item->boundingRect();
    QPointF topLeftOffset = boundingRect.topLeft();

    // 对齐到网格
    const int gridSize = 20;
    qreal alignedX = round((randomPos.x() + topLeftOffset.x()) / gridSize) * gridSize;
    qreal alignedY = round((randomPos.y() + topLeftOffset.y()) / gridSize) * gridSize;

    // 设置图形项位置
    item->setPos(alignedX - topLeftOffset.x(), alignedY - topLeftOffset.y());

    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actionText_triggered()
{
    QString str = QInputDialog::getText(this,"输入对话框","请输入文本：");
    QGraphicsTextItem *item = new QGraphicsTextItem(str);
    item->setFlags(QGraphicsItem::ItemIsSelectable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsMovable);

    QFont font;
    font.setPointSize(5);
    font.setFamily("微软雅黑");
    item->setFont(font);
    item->setDefaultTextColor(Qt::darkCyan);
    item->setZValue(zValue++);
    item->setData(ITEM_ID,item_id++);
    item->setData(ITEM_DESCRIPTION,"直线");
    item->setPos(qrand()%100-60,qrand()%100-60);

    scene->addItem(item);
    scene->clearSelection();
    item->setSelected(true);
}

void MainWindow::on_actionMagnify_triggered()
{
    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item = scene->selectedItems().at(i);
        item->setScale(item->scale() + 0.1);
    }
}

void MainWindow::on_actionDownsize_triggered()
{
    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item = scene->selectedItems().at(i);
        item->setScale(item->scale() - 0.1);
    }
}

void MainWindow::on_actionRestore_triggered() //待补充
{
    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item = scene->selectedItems().at(i);
        item->setRotation(0);
        item->setScale(1.0);
    }
}

void MainWindow::on_actionLeft_triggered()
{
    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item = scene->selectedItems().at(i);
        item->setRotation(item->rotation() - 5);
    }
}

void MainWindow::on_actionRight_triggered()
{
    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item = scene->selectedItems().at(i);
        item->setRotation(item->rotation() + 5);
    }
}

void MainWindow::on_actionPre_triggered()
{
    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item = scene->selectedItems().at(i);
        item->setZValue(item->zValue() + 1);
    }
}

void MainWindow::on_actionRear_triggered()
{
    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item = scene->selectedItems().at(i);
        item->setZValue(item->zValue() - 1);
    }
}

void MainWindow::on_actionCombine_triggered()
{
    QGraphicsItemGroup *group = new QGraphicsItemGroup;
    group->setFlags(QGraphicsItem::ItemIsSelectable |
                   QGraphicsItem::ItemIsFocusable |
                   QGraphicsItem::ItemIsMovable);

    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item = scene->selectedItems().at(0);
        item->setSelected(false);
        item->clearFocus();

        group->addToGroup(item);
    }

    scene->addItem(group);
    group->setSelected(true);
    group->setFocus();
}

void MainWindow::on_actionApart_triggered()
{
    //拷贝选中的项到列表中
    QList<QGraphicsItem*>selectedItems = scene->selectedItems();

    int count = scene->selectedItems().count();

    for(int i = 0;i<count;i++)
    {
        QGraphicsItemGroup *group = (QGraphicsItemGroup*)selectedItems.at(i);
        scene->destroyItemGroup(group);
    }
}

void MainWindow::on_actionDelete_triggered()
{
    QList<QGraphicsItem*>selectedItems = scene->selectedItems();

    int count = scene->selectedItems().count();
    for(int i = 0;i<count;i++)
    {
        QGraphicsItem *item =selectedItems.at(i);
        scene->removeItem(item);
    }
}

void MainWindow::on_actionExit_triggered()
{
    this->close();
}

void MainWindow::drawGridBackground()
{
    //网格间隔
    const int gridSize = 20;

    QPixmap gridPixmap(gridSize,gridSize);
    gridPixmap.fill(Qt::white);

    QPainter painter(&gridPixmap);
    painter.setPen(QPen(Qt::lightGray));
    painter.drawLine(0,0,0,gridSize);
    painter.drawLine(gridSize,0,gridSize,gridSize);
    painter.drawLine(0,0,gridSize,0);
    painter.drawLine(0,gridSize,gridSize,gridSize);

    scene->setBackgroundBrush(QBrush(gridPixmap));
}

void MainWindow::saveSymbols(const QString&fileName)
{
    if(fileName.isEmpty())
        return;

    QJsonArray itemsArray; // Json数组用于保存已绘制符号信息

    for(QGraphicsItem *item : scene->items())
    {
        QJsonObject itemObject;

        // 保存通用属性
        itemObject["x"] = item->x();
        itemObject["y"] = item->y();
        itemObject["rotation"] = item->rotation();
        itemObject["scale"] = item->scale();
        itemObject["type"] = item->type();
        // 保存具体图元类型的属性
        if(auto rectItem = qgraphicsitem_cast<QGraphicsRectItem*>(item))
        {
            itemObject["shape"] = "rectangle";
            itemObject["width"] = rectItem->rect().width();
            itemObject["height"] = rectItem->rect().height();
            itemObject["color"] = rectItem->brush().color().name(); // 颜色的名字
        }
        else if(auto ellipseItem = qgraphicsitem_cast<QGraphicsEllipseItem*>(item))
        {
            itemObject["shape"] = "ellipse";
            itemObject["width"] = ellipseItem->rect().width();
            itemObject["height"] = ellipseItem->rect().height();
            itemObject["color"] = ellipseItem->brush().color().name();
        }
        else if(auto polygonItem = qgraphicsitem_cast<QGraphicsPolygonItem*>(item))
        {
            itemObject["shape"] = "polygon";
            QJsonArray pointsArray;
            for(const QPointF &point : polygonItem->polygon())
            {
                QJsonObject pointObject;
                pointObject["x"] = point.x();
                pointObject["y"] = point.y();
                pointsArray.append(pointObject);
            }
            itemObject["points"] = pointsArray;
            itemObject["color"] = polygonItem->brush().color().name();
        }
        else if(auto lineItem = qgraphicsitem_cast<QGraphicsLineItem*>(item))
        {
            itemObject["shape"] = "line";
            itemObject["x1"] = lineItem->line().x1();
            itemObject["x2"] = lineItem->line().x2();
            itemObject["y1"] = lineItem->line().y1();
            itemObject["y2"] = lineItem->line().y2();

            itemObject["color"] = lineItem->pen().color().name();
            itemObject["width"] = lineItem->pen().width();
        }

        itemsArray.append(itemObject);
    }

    QJsonDocument doc(itemsArray);
    QFile file(fileName);
    if(!file.open(QIODevice::WriteOnly))
        return;
    file.write(doc.toJson());
    file.close();
}

void MainWindow::loadSymbols(const QString&fileName)
{
    if(fileName.isEmpty())
        return;
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly))
        return;

    QByteArray data = file.readAll(); // 用QByteArray接收Json文件数据
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(data); // 又形成Json文件
    QJsonArray itemsArray = doc.array(); // 又形成JsonArray

    for(const QJsonValue &value : itemsArray) // JsonArray里面是JsonValue
    {
        QJsonObject itemObject = value.toObject();
        QString shape = itemObject["shape"].toString();

        QGraphicsItem *item = nullptr;

        if(shape == "rectangle")
        {
            QGraphicsRectItem *rectItem = new QGraphicsRectItem(-(itemObject["width"].toDouble()/2),-(itemObject["height"].toDouble()/2),itemObject["width"].toDouble(),itemObject["height"].toDouble());
            rectItem->setBrush(QBrush(QColor(itemObject["color"].toString())));
            item = rectItem;
        }
        else if(shape == "ellipse")
        {
            QGraphicsEllipseItem *ellipseItem = new QGraphicsEllipseItem(-(itemObject["width"].toDouble()/2),-(itemObject["height"].toDouble()/2),itemObject["width"].toDouble(),itemObject["height"].toDouble());
            ellipseItem->setBrush(QBrush(QColor(itemObject["color"].toString())));
            item = ellipseItem;
        }
        else if(shape == "polygon")
        {
            QPolygonF polygon;
            QJsonArray pointsArray = itemObject["points"].toArray();
            for(const QJsonValue& pointValue : pointsArray)
            {
                QJsonObject pointObject = pointValue.toObject();
                polygon << QPointF(pointObject["x"].toDouble(),pointObject["y"].toDouble());
            }
            QGraphicsPolygonItem *polygonItem = new QGraphicsPolygonItem(polygon);
            polygonItem->setBrush(QBrush(QColor(itemObject["color"].toString())));
            item = polygonItem;
        }
        else if(shape == "line")
        {
            QLineF line(itemObject["x1"].toDouble(), itemObject["y1"].toDouble(),
                                    itemObject["x2"].toDouble(), itemObject["y2"].toDouble());
            QGraphicsLineItem* lineItem = new QGraphicsLineItem(line);
            QPen pen;
            pen.setColor(QColor(itemObject["color"].toString()));
            pen.setWidth(itemObject["width"].toInt());
            lineItem->setPen(pen);
            // 设置旋转中心为直线的中点
            QPointF center = line.center();
            lineItem->setTransformOriginPoint(center);

            item = lineItem;
        }

        if(item)
        {
            // 设置通用属性
            item->setPos(itemObject["x"].toDouble(), itemObject["y"].toDouble()); // toDouble()
            item->setRotation(itemObject["rotation"].toDouble());
            item->setScale(itemObject["scale"].toDouble());
            item->setFlags(QGraphicsItem::ItemIsMovable |
                           QGraphicsItem::ItemIsSelectable |
                           QGraphicsItem::ItemIsFocusable);

            scene->addItem(item);
        }
    }
}

void MainWindow::on_actionSaveSymbols_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this,"保存符号",QDir::currentPath(),"JSON Files(*.json)");
    if(!fileName.isEmpty())
        saveSymbols(fileName);
}

void MainWindow::on_actionLoadSymbols_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,"加载符号",QDir::currentPath(),"JSON Files(*.json)");
    if(!fileName.isEmpty())
        loadSymbols(fileName);
}

void MainWindow::on_actionSymbolLibrary_triggered()
{
    SymbolLibraryDialog dialog(this);
    connect(&dialog,&SymbolLibraryDialog::addSymbolInLib,this,[this](QString fileName)
    {
        saveSymbols(fileName);
    });
    connect(&dialog,&SymbolLibraryDialog::symbolSelected,this,[this](QString fileName)
    {
        loadSymbols(fileName);
    });
    dialog.exec();
}
